package com.atguigu.spzx.manager.service.impl;

import cn.hutool.core.lang.UUID;
import com.atguigu.spzx.common.exception.GuiguException;
import com.atguigu.spzx.manager.properties.SpzxMinioProperties;
import com.atguigu.spzx.manager.service.FileService;
import com.atguigu.spzx.manager.util.MinioUtil;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import io.minio.errors.*;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@Service
public class FileServiceImpl implements FileService {

    @Override
    public String upload(MultipartFile file, String module) {
        //校验参数：
        if(!StringUtils.hasLength(module)||
            file.isEmpty()){
            throw new GuiguException(ResultCodeEnum.LOGIN_PARAMS_ERROR);
        }

        try {
            //获取前端上传文件的名称
            String originalFilename = file.getOriginalFilename();
            //桶内文件名
            String objectName = System.currentTimeMillis()+"_"
                    + UUID.randomUUID().toString().substring(0,6)
                    + originalFilename.substring(originalFilename.lastIndexOf("."));

            objectName = module+new DateTime()
                    .toString("/yyyy/MM/dd/")+objectName;
            MinioUtil.build().putObject(
                    PutObjectArgs.builder()
                            .bucket(SpzxMinioProperties.BUCKET)//保存文件的桶
                            .stream(file.getInputStream(), file.getInputStream().available() ,-1)//上传的文件信息：参数1-文件输入流 参数2-文件的字节数  参数3-分片 -1不分片
                            .object(objectName) //桶内保存文件的路径+文件名称
                            .build()
            );
            //可以根据前面配置的参数拼接出上传后文件的访问路径
            String path = SpzxMinioProperties.ENDPOINT+"/"+SpzxMinioProperties.BUCKET+"/"+objectName;
            return path;
        } catch (Exception e) {
            throw new GuiguException(ResultCodeEnum.UPLOAD_ERROR);
        }
    }

    @Override
    public void delete(String path) {
        try {
            MinioClient minioClient = MinioUtil.build(); //客户端 连接指定的minio服务器
            String objectName = path.substring((SpzxMinioProperties.ENDPOINT+"/"
                    +SpzxMinioProperties.BUCKET+"/").length());
            minioClient.removeObject(
                    RemoveObjectArgs.builder()
                            .bucket(SpzxMinioProperties.BUCKET)  //删除文件所在的桶
                            .object(objectName) //删除文件在桶内的路径 +文件名
                            .build()
            );
        } catch (Exception e) {
            throw new GuiguException(ResultCodeEnum.FILE_DELETE_ERROR);
        }
    }
}
